<template>
  <div class="shop_member_detail">
    <Row class="shop_member_detail_edit" type="flex" justify="space-between">
      <Row>
        <div class="list-title">
          <span></span>
          <h3>会员档案</h3>
        </div>
      </Row>

      <Row>
        <Form class="from" ref="search" label-position="left" inline>
          <FormItem :label-width="72">
            <div slot="label" style="transform: translateX(12px);">门店名称：</div>
            <span>{{ $route.params.shopName || '万达店' }}</span>
          </FormItem>
          <FormItem :label-width="72">
            <div slot="label" style="transform: translateX(12px);">会员编号：</div>
            <span>{{ $route.params.memberId|| 'CS04012745' }}</span>
            <!-- <Input v-model="searchObj.memberIdOrCardNo" autocomplete="off" placeholder="请输入" /> -->
          </FormItem>
          <FormItem :label-width="60">
            <div slot="label" style="transform: translateX(12px);">时间：</div>
            <!-- <datePickerYmd @on-change="search"
                           :dateOption="dateOption"
                           :selectDateType.sync="selectDateType "
                           v-model="timeDate"></datePickerYmd> -->
                <RadioGroup
      style="margin-right: 10px"
      v-model="selectDateType"
      @on-change="search"
      type="button"
    >
      <Radio v-for="(item, index) in dataType" :key="index"  :label="item.key">
        <span>{{item.type}}</span>
      </Radio>
    </RadioGroup>
            <DatePicker @on-change="search" :options="dateOption" v-show="item.key === selectDateType" v-for="(item, index) in dataType" :key="index" :type="item.key" v-model="item.value" placeholder="Select date" style="width: 200px"></DatePicker>
          </FormItem>
          <FormItem>
            <Button type="primary" @click="search" class="coinrevenue-btn">查询</Button>
          </FormItem>
        </Form>
      </Row>
    </Row>
    <Row class="shop_member_message">
      <div class="ivu-table-wrapper">
        <div class="ivu-table">
          <div class="ivu-table-body">
            <table cellspacing="0" cellpadding="0" border="0" style="width: 100%">
              <tbody class="ivu-table-tbody">
                <tr v-for="(item, index) in memberRecord" :key="index" class="ivu-table-row">
                  <td v-for="(ele, k) in item" :key="k" class="ivu-table-column-Cj75un">
                    <div
                      v-if="ele.key === 'action'"
                      style="color: #2D8CF0; cursor:pointer;"
                      class="ivu-table-cell"
                    >
                      <span>{{ele.label}}{{ele.value}}</span>
                    </div>
                    <div v-else class="ivu-table-cell">
                      <span>{{ele.label}}{{ele.value}}</span>
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </Row>
    <div v-if="memberId">
      <Row class="shop_member_message">
        <RadioGroup v-model="activeTable" @on-change="handleTable" type="button">
          <Radio :label="item" v-for="(item, index) in tableOption" :key="index"></Radio>
        </RadioGroup>
      </Row>
      <div v-if="activeIndex !== 3" style="padding-top:0" class="list-title shop_member_message">
        <span></span>
        <!-- <h3>原微信会员、实体卡会员未转入人数： 13,483</h3> -->
        <div style="display: flex;flex-wrap: wrap;">
          <p>
            "{{activeTable}}" 统计摘要时间：
            <em class="text">{{ dayjs(startDate).format('YYYY-MM-DD') }} 一 {{dayjs(endDate).subtract(1, 'day').format('YYYY-MM-DD')}}</em>
            日期间；
          </p>
          <p v-for="(item, index) in summaryComputed" :key="index">
            {{item.label}}
            <em class="text">{{item.value}}</em>
            {{item.unit}} {{index === 0 ? '，' : index === (summaryComputed.length -1) ? '。' : ',' }}
          </p>
        </div>

      </div>
      <Table :maxHeight="resData.length > 10 ? 530 : 0" :loading="isloading" border stripe ref="rowSpanTable" :columns="columns" :data="resData"></Table>
      <div v-show="activeIndex !== 3" class="page-box" style="margin-top: 20px">
        <Page
          :total="total"
          ref="pages"
          :current.sync="searchObj.pageIndex"
          :page-size="searchObj.limit"
          @on-change="handlePage"
          @on-page-size-change="handlePageSize"
          show-sizer
          show-total
        />
      </div>
    </div>

  </div>
</template>

<script>
// {"merchantId":"dwj","shopId":"9b07be4d-9030-451b-9f28-2b191eb5a141","startDate":"2019-04-28 00:00:00","endDate":"2019-10-28 23:59:59","memberId":"840060547905"}
// {"memberIdOrCardNo":"CS04012745","merchantId":"dwj","shopId":"9b07be4d-9030-451b-9f28-2b191eb5a141"}
import {
  memberDetails,
  memberCatd,
  memberBuy,
  membeChange,
  memberPlay,
  memberPlaySummary,
  membeChangeSummary,
  memberBuySummary
} from '@/api/report/shop'
import dayjs from 'dayjs'
import datePickerYmd from '@/components/date-picker-ymd/date-picker-ymd.vue'
import iSelectShop from '@/components/i-select-shop'
const ORDER_TYPE = {
  3: '游戏币订单',
  4: '游戏券订单',
  5: '游戏卡订单',
  6: '休闲项目订单',
  7: '商品订单',
  8: '礼品订单',
  9: '团购订单',
  10: '兑换券订单',
  11: '办卡押金订单',
  12: '手工或导入订单',
  13: '其他订单',
  14: '银票卡订单',
  15: '商铺租赁订单',
  16: '废品收入订单',
  17: '租赁押金订单',
  18: '机台租赁订单',
  19: '会员补卡订单',
  20: '特殊团购订单',
  21: '套餐订单'
}
export default {
  name: 'report_shop_member_detail',
  components: { datePickerYmd, iSelectShop },
  data () {
    return {
      searchObj: {
        shopId: this.$store.state.user.orgId,
        merchantId: this.$store.state.user.merchantId,
        limit: 10,
        pageIndex: 1,
        offset: 0,
        memberIdOrCardNo: 'CS04012745'
      },
      memberId: '', // 会员id
      dayjs: dayjs,
      total: 0,
      activeTable: '购买明细',
      tableOption: ['购买明细', '存取兑明细', '游玩明细', '卡片记录'],
      resData: [],
      shopList: [],
      isloading: false,
      selectDateType: 'daterange',
      dataType: [
        { type: '日', key: 'date', value: new Date() },
        { type: '月', key: 'month', value: new Date() },
        { type: '自定义', key: 'daterange', value: [dayjs().subtract(6, 'month').format('YYYY-MM-DD 00:00:00'), dayjs().format('YYYY-MM-DD 00:00:00')] }
      ],
      // timeDate: [dayjs().subtract(6, 'month').format('YYYY-MM-DD 00:00:00'), dayjs().format('YYYY-MM-DD 00:00:00')],
      dateOption: {
        disabledDate (date) {
          return dayjs(date).isAfter(dayjs(new Date()))
        }
      },
      // 会员档案
      memberRecord: [
        [
          { label: '姓名：', value: '', key: 'memberName' },
          { label: '会员卡号：', value: '', key: 'cardNo' },
          { label: '电话：', value: '', key: 'mobileNumber' },
          { label: '游戏币：', value: '', key: 'coin' },
          { label: '游戏券：', value: '', key: 'totalTimes' },
          { label: '彩票余额：', value: '', key: 'lottery' }
        ],
        [
          { label: '年龄：', value: '', key: 'age' },
          { label: '证件号码：', value: '', key: 'idNumber' },
          { label: '等级：', value: '', key: 'levelCode' },
          { label: '可用积分：', value: '', key: 'currentIntegral' },
          { label: '累计积分：', value: '', key: 'accumulatedIntegral' },
          { label: '', value: '', key: '' }
        ],
        [
          { label: '性别：', value: '', key: 'gender' },
          { label: '注册日期：', value: '', key: 'sendTime' },
          { label: '', value: '', key: 'action' },
          { label: '消费次数：', value: '', key: 'countAll' },
          { label: '累计消费：', value: '', key: 'payMoney' },
          { label: '', value: '', key: '' }
        ]
      ],
      columns0: [
        { title: '购买日期', key: 'createTime', align: 'center' },
        { title: '所购商品', key: 'goodsName', align: 'center' },
        { title: '所购金额(元)', key: 'totalFee', align: 'center' },
        { title: '购币数(枚)', key: 'saleQuantity', align: 'center' },
        { title: '赠币数(枚)', key: 'giveQuantity', align: 'center' },
        { title: '购券数(局)', key: 'saleGameCouponRound', align: 'center' },
        { title: '赠券数(局)', key: 'giveGameCouponRound', align: 'center' },
        { title: '积分值', key: 'changeNum', align: 'center' },
        { title: '订单类型',
          key: 'orderType',
          align: 'center',
          render: (h, params) => {
            return h('span', ORDER_TYPE[params.row.orderType])
          }
        },
        // { title: '积分类型', key: 'originShopName', align: 'center' },
        // { title: '消费类型', key: 'originShopName', align: 'center' },
        { title: '操作地点', key: 'deviceName', align: 'center' },
        { title: '操作人', key: 'cashierName', align: 'center' }
      ],
      columns1: [
        { title: '操作时间', key: 'createTime', align: 'center' },
        { title: '游戏币(枚)', key: 'coin', align: 'center' },
        { title: '游戏券(局)  ', key: 'gameTicket', align: 'center' },
        { title: '彩票(张)', key: 'lottery', align: 'center' },
        { title: '操作地点', key: 'createPosName', align: 'center' },
        { title: '操作人', key: 'creatorName', align: 'center' },
        { title: '备注', key: 'remark', align: 'center' }
      ],
      columns2: [
        { title: '操作时间', key: 'createTime', align: 'center' },
        { title: '游戏币', key: 'coin', align: 'center' },
        { title: '游戏券  ', key: 'gameTicket', align: 'center' },
        { title: '彩票', key: 'lottery', align: 'center' },
        { title: '机台名称', key: 'machineInstanceName', align: 'center' },
        { title: '投币口', key: 'machineSlot', align: 'center' },
        { title: '备注', key: 'remark', align: 'center' }
      ],
      columns3: [
        { title: '操作时间', key: 'createTime', align: 'center' },
        { title: '卡号', key: 'cardNo', align: 'center' },
        { title: '操作类型  ', key: 'operateType', align: 'center' },
        { title: '操作人', key: 'creatorName', align: 'center' },
        { title: '备注', key: 'remark', align: 'center' }
      ],
      summaryBuy: [
        { label: '本会员订单总额', key: 'totalFeeCount', value: '', unit: '元' },
        { label: '游戏币购买总数', key: 'saleQuantityCount', value: '', unit: '枚' },
        { label: '赠送总数', key: 'giveQuantityCount', value: '', unit: '枚' },
        { label: '游戏券购买总数', key: 'saleGameCouponRound', value: '', unit: '局' },
        { label: '赠送总数', key: 'giveGameCouponRound', value: '', unit: '局' }
      ],
      summaryChange: [
        { label: '本会员游戏币存入总数', key: 'saveCoin', value: '', unit: '枚' },
        { label: '取出总数', key: 'fetchCoin', value: '', unit: '枚' },
        { label: '游戏券存入总数', key: 'saveGameTicket', value: '', unit: '局' },
        { label: '取出总数', key: 'fetchGameTicket', value: '', unit: '局' },
        { label: '彩票手工存入总数', key: 'saveLottery', value: '', unit: '张' },
        { label: '兑换扣减总数', key: 'fetchLottery', value: '', unit: '张' }
      ],
      summaryPay: [
        { label: '本会员游戏币在刷卡器刷卡总扣减', key: 'coin', value: '', unit: '枚' },
        { label: '游戏券总扣减', key: 'gameTicket', value: '', unit: '局' },
        { label: '电子彩票总共出', key: 'lottery', value: '', unit: '张' }
      ]
    }
  },
  computed: {
    columns () {
      // let index = this.tableOption.indexOf(this.activeTable)
      return this[`columns${this.activeIndex}`]
    },
    activeIndex () {
      return this.tableOption.indexOf(this.activeTable)
    },
    summaryComputed () {
      const summary = [this.summaryBuy, this.summaryChange, this.summaryPay]
      return summary[this.activeIndex] || []
    },
    timeDate () {
      // let time = this.dataType.filter(item => item.key === this.selectDateType)
      let value = this.dataType.filter(item => item.key === this.selectDateType).map(item => item.value)[0]
      //  this.initValue[this.currentDateType]
      let startDate, endDate
      // let dateArr
      if (this.selectDateType === 'daterange') {
        startDate = dayjs(value[0]).format('YYYY-MM-DD 00:00:00')
        endDate = dayjs(value[1]).format('YYYY-MM-DD 00:00:00')
        // dateArr = [,
        //  ]
      } else if (this.selectDateType === 'month') {
        startDate = dayjs(value).format('YYYY-MM-01 00:00:00')

        endDate = dayjs(value)
          .add(1, 'month')
          .format('YYYY-MM-01 00:00:00')
        if (dayjs().isBefore(endDate)) {
          endDate = dayjs().format('YYYY-MM-DD 00:00:00')
          // 判断是否需要加时间
          if (!this.dateOption.disabledDate(new Date(endDate))) {
            endDate = dayjs(endDate)
              .add(1, 'day')
              .format('YYYY-MM-DD 00:00:00')
          }
        }

        // endDate = dayjs().isAfter(dayjs(value).add(1, 'month'))
        // dateArr = [
        //   dayjs(value).format('YYYY-MM-01 00:00:00'),
        //   dayjs(value)
        //     .add(1, 'month')
        //     .format('YYYY-MM-01 00:00:00')
        // ]
      } else if (this.selectDateType === 'year') {
        startDate = dayjs(value).format('YYYY-01-01 00:00:00')

        endDate = dayjs(value)
          .add(1, 'year')
          .format('YYYY-01-01 00:00:00')
        if (dayjs().isBefore(endDate)) {
          endDate = dayjs().format('YYYY-MM-DD 00:00:00')
          // 判断是否需要加时间
          if (!this.dateOption.disabledDate(new Date(endDate))) {
            endDate = dayjs(endDate)
              .add(1, 'day')
              .format('YYYY-MM-DD 00:00:00')
          }
        }

        // dateArr = [
        //   dayjs(value).format('YYYY-01-01 00:00:00'),
        //   dayjs(value)
        //     .add(1, 'year')
        //     .format('YYYY-01-01 00:00:00')
        // ]
      } else if (this.selectDateType === 'date') {
        startDate = dayjs(value).format('YYYY-MM-DD 00:00:00')
        endDate = dayjs(value)
          .add(1, 'day')
          .format('YYYY-MM-DD 00:00:00')
        // dateArr = [
        //   dayjs(value).format('YYYY-MM-DD 00:00:00'),
        //   dayjs(value)
        //     .add(1, 'day')
        //     .format('YYYY-MM-DD 00:00:00')
        // ]
      }
      return [startDate, endDate]
    },
    startDate () {
      return this.timeDate[0]
    },
    endDate () {
      if (this.selectDateType === 'daterange') {
        return dayjs(this.timeDate[1])
          .add(1, 'day')
          .format('YYYY-MM-DD 00:00:00')
      }
      return this.timeDate[1]
    }
  },
  created () {
    this.searchObj.memberIdOrCardNo = this.$route.params.memberId
    this.searchObj.shopId = this.$route.params.shopId
    this.getDetail(true)
    // console.log(this.$route.params)
  },
  methods: {
    handleTable (val) {
      this.searchObj.limit = 10
      this.searchObj.pageIndex = 1
      this.searchObj.offset = 0
      this.getList()
      this.summary()
      // console.log(val, this.activeIndex)
    },
    // 搜索
    search () {
      this.searchObj.limit = 10
      this.searchObj.pageIndex = 1
      this.searchObj.offset = 0
      this.getDetail(true)
    },
    handlePageSize (val) {
      this.searchObj.limit = val
      this.searchObj.offset = 0
      if (this.searchObj.pageIndex === 1) {
        this.getList()
        this.summary()
      } else {
        this.searchObj.pageIndex = 1
      }
      // this.getShopList()
    },
    handlePage (val) {
      this.searchObj.offset = (val - 1) * this.searchObj.limit
      this.getList()
      this.summary()
    },
    async getDetail (search) { // search 是否点击搜索按钮或者搜索条件变化
      let { memberIdOrCardNo, merchantId, shopId } = this.searchObj
      const res = await memberDetails({
        shopId,
        merchantId,
        memberId: memberIdOrCardNo
      })
      if (res.data.status !== 200) return this.$Message.error(`${res.data.error}`)
      const keys = Object.keys(res.data.data)
      this.memberRecord = this.memberRecord.map(item => {
        item.forEach(ele => {
          if (keys.includes(ele.key)) {
            if (ele.key === 'gender') {
              ele.value = ['男', '女'][res.data.data[ele.key]]
            } else {
              ele.value = res.data.data[ele.key]
            }
          }
        })
        return item
      })
      this.memberId = res.data.data && res.data.data.memberId
      if (search) {
        this.getList()
        this.summary()
      }
    },
    // 获取表格数据
    async getList () {
      const api = [memberBuy, membeChange, memberPlay, memberCatd]
      this.isloading = true
      const res = await api[this.activeIndex]({
        ...this.searchObj,
        memberId: this.memberId,
        startDate: this.startDate,
        endDate: this.endDate
      })
      this.resData = []
      this.isloading = false
      if (res.data.status !== 200) {
        return this.$Message.error(`${res.data.error}`)
      }
      if (this.activeIndex === 1) {
        let keys = ['coin', 'lottery', 'gameTicket']
        this.resData = (res.data.data || []).map(item => {
          let sign = ['+', '-'][item.changeFlag]
          for (let index = 0; index < keys.length; index++) {
            const key = keys[index]
            if (item[key]) {
              item[key] = `${sign}${item[key]}`
            }
          }
          return item
        })
      } else {
        this.resData = res.data.data || []
      }
      this.total = res.data.totalCount || 0
    },
    // 获取统计数据
    async summary () {
      const api = [memberBuySummary, membeChangeSummary, memberPlaySummary]
      let params = {
        ...this.searchObj,
        memberId: this.memberId,
        startDate: this.startDate,
        endDate: this.endDate
      }
      if (api[this.activeIndex]) {
        const res = await api[this.activeIndex](params)

        if (res.data.status !== 200) return this.$Message.error(`${res.data.error}`)
        const summary = [this.summaryBuy, this.summaryChange, this.summaryPay]
        summary[this.activeIndex] = summary[this.activeIndex].map(item => {
          item.value = (res.data.data || {})[item.key]
          return item
        })
      }
    }
  }
}
</script>

<style lang="less" scoped>
.shop_member_detail {
  .shop_member_detail_edit {
    padding-top: 20px;
    padding-left: 20px;
    padding-right: 20px;
    margin-bottom: -4px;
  }
  .list-title {
    display: flex;
    height: 100%;
    align-items: center;
    padding-bottom: 20px;
    font-size: 14px;
    color: #464c5b;
    letter-spacing: 0;
    text-align: justify;
    // font-size: 20px;
    // margin-bottom: 20px;
    span {
      height: 20px;
      width: 8px;
      background: #2d8cf0;
      margin-right: 15px;
    }
    .text{
      font-style: normal;
      color: orange;
    }
  }
  .shop_member_message {
    padding-top: 20px;
    padding-left: 20px;
    padding-right: 20px;
    padding-bottom: 20px;
  }
  .border-rignt {
    border-right: 1px solid #e8eaec;
  }
  .ivu-table {
    padding: 10px;
    background: #f8f8f9;
  }
  .ivu-table td {
    background: #f8f8f9;
  }
  .ivu-table td {
    border-bottom: none;
  }
  .ivu-radio-group-button .ivu-radio-wrapper-checked {
    background: #2d8cf0;
    color: #fff;
  }
}
</style>
